package com.example.demo.service.impl;

import com.example.demo.Mapper.BookBorrowMapper;
import com.example.demo.Mapper.BookMapper;
import com.example.demo.Mapper.FeeRecordMapper;
import com.example.demo.Mapper.UserMapper;
import com.example.demo.core.BorrowUtil;
import com.example.demo.core.BookBackInfo;
import com.example.demo.core.NotFoundException;
import com.example.demo.model.*;
import com.example.demo.service.BookBorrowAndFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookBorrowAndFeeServiceImp implements BookBorrowAndFeeService {
    @Autowired
    public FeeRecordMapper feeRecordMapper;

    @Autowired
    public BookBorrowMapper bookBorrowMapper;

    @Autowired
    public BookMapper bookMapper;

    @Autowired
    public UserMapper userMapper;


    private Integer findUseridByName(String name) throws NotFoundException {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andUserNameEqualTo(name);
        List<User> list=userMapper.selectByExample(userExample);

        if(list.size()==0)
            throw new NotFoundException("用户名不存在");
        else
            return list.get(0).getUserId();
    }

    private BookBorrow findBookBorrowUserIdAndBookInfoId(Integer userId,Integer bookinfoId,String errorMessage) throws NotFoundException {
        BookBorrowExample bookBorrowExample=new BookBorrowExample();
        BookBorrowExample.Criteria criteria=bookBorrowExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andBookinfoIdEqualTo(bookinfoId);
        criteria.andIfBackEqualTo(0);
        List<BookBorrow> list=bookBorrowMapper.selectByExample(bookBorrowExample);

        if(list.size()==0)
            throw new NotFoundException(errorMessage);
        else
            return list.get(0);
    }

    private List<BookBorrow> findBookBorrowUserIdAndIfback(Integer userId,Integer ifback) throws NotFoundException {
        BookBorrowExample bookBorrowExample=new BookBorrowExample();
        BookBorrowExample.Criteria criteria=bookBorrowExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andIfBackEqualTo(1);
        return bookBorrowMapper.selectByExample(bookBorrowExample);
    }

    @Override
    public boolean isBorrow(Integer bookInfoId,Integer userId) {
        BookBorrowExample bookBorrowExample=new BookBorrowExample();
        BookBorrowExample.Criteria criteria=bookBorrowExample.createCriteria();
        if(bookInfoId!=null)
            criteria.andBookinfoIdEqualTo(bookInfoId);
        if(userId!=null)
            criteria.andUserIdEqualTo(userId);
        criteria.andIfBackEqualTo(0);

        List<BookBorrow> list=bookBorrowMapper.selectByExample(bookBorrowExample);

        return list.size()!=0;
    }


    @Override
    public boolean bookBorrow(String name, Integer bookinfoId,Integer day) throws NotFoundException {
        Integer userId=findUseridByName(name);

        if(bookBorrowMapper
                .insertSelective(new BookBorrow(null
                , userId
                , bookinfoId
                , new Date(System.currentTimeMillis())
                ,new Date(System.currentTimeMillis()+ BorrowUtil.dayTime*day)
                ,0
                ,null
                ,null
                ,null
                ,null
                ,null,null))==1)
            return true;
        return false;
    }

    @Override
    public boolean bookRenew(Integer bookborrowId,Integer day) {

        BookBorrow bookBorrow=bookBorrowMapper.selectByPrimaryKey(bookborrowId);
        Book book=bookMapper.selectByPrimaryKey(bookBorrow.getBookinfoId());
        //达到最大续借次数
        if(book.getMaxRenewCnt().equals(bookBorrow.getRenewCnt()))
            return false;
        //超期的书不允许续借
        if (bookBorrow.getTimeNeedBack().getTime()<=System.currentTimeMillis())
            return false;

        bookBorrow.setRenewCnt(bookBorrow.getRenewCnt()+1);
        bookBorrow.setTimeNeedBack(new Date(bookBorrow.getTimeNeedBack().getTime()+ BorrowUtil.dayTime*day));

        return bookBorrowMapper.updateByPrimaryKey(bookBorrow) == 1;
    }

    @Override
    public BookBackInfo bookBack(String name, Integer bookinfoId) throws NotFoundException {
        Integer userId=findUseridByName(name);

        BookBorrow bookBorrow= findBookBorrowUserIdAndBookInfoId(userId,bookinfoId,"未还书的借阅记录不存在");

        if (bookBorrow.getTimeNeedBack().getTime()<=System.currentTimeMillis())
        {
            DecimalFormat df =new DecimalFormat("#.00");
            DecimalFormat df2 =new DecimalFormat("#");
            return new BookBackInfo(df.format(BorrowUtil.feePerDay*(System.currentTimeMillis()-bookBorrow.getTimeNeedBack().getTime())/(24 * 60 * 60 * 1000.0))
                    ,df2.format((System.currentTimeMillis()-bookBorrow.getTimeNeedBack().getTime())/(24 * 60 * 60 * 1000.0))
                    ,bookBorrow.getTimeBorrrow()
                    ,bookBorrow.getTimeNeedBack()
                    );
        }

        //不需要还款，直接还书
        bookBorrow.setTimeBack(new Date(System.currentTimeMillis()));
        bookBorrow.setIfBack(1);
        bookBorrowMapper.updateByPrimaryKey(bookBorrow);

        return new BookBackInfo("0"
                ,"0"
                ,bookBorrow.getTimeBorrrow()
                ,bookBorrow.getTimeNeedBack()
        );
    }

    /**
     * 罚款记录
     * @param name
     * @param timePayFeeStartDate
     * @param timePayFeeEndDate
     * @return
     */
    @Override
    public List<FeeRecordNameMap> selectFeeRecord(String name,Date timePayFeeStartDate,Date timePayFeeEndDate) throws NotFoundException {


        return feeRecordMapper.selectFourTableByExample(new FeeRecordSearchPara(name,timePayFeeStartDate,timePayFeeEndDate));
    }

    @Override
    public List<BookBorrow> selectBorrowRecord(String name,String bookName) throws NotFoundException {
        BookBorrowExample bookBorrowExample=new BookBorrowExample();
        BookBorrowExample.Criteria criteria=bookBorrowExample.createCriteria();

        if (name!=null)
            criteria.andUserIdEqualTo(findUseridByName(name));
        if (bookName!=null)
            criteria.andBooknameEqualTo(bookName);

        return bookBorrowMapper.selectByExample(bookBorrowExample);
    }

    @Override
    public boolean feePay(String name,Integer bookinfoId) throws NotFoundException {

        //根据name与book infoId查找相应借阅记录以获得借阅记录的bookborrowId(借阅记录id)
        Integer userId=findUseridByName(name);
        BookBorrow bookBorrow=findBookBorrowUserIdAndBookInfoId(userId,bookinfoId,"未还款记录不存在");

        //插入还款记录
        feeRecordMapper.insertSelective(new FeeRecord(null
                ,BorrowUtil.feePerDay*(System.currentTimeMillis()-bookBorrow.getTimeNeedBack().getTime())/(24 * 60 * 60 * 1000.0)
                ,bookBorrow.getBookborrowId()
                ,new Date(System.currentTimeMillis())
                ,null
                ,"1"
        ));

        //还款的时候同时还书
        bookBorrow.setTimeBack(new Date(System.currentTimeMillis()));
        bookBorrow.setIfBack(1);

        if(bookBorrowMapper.updateByPrimaryKey(bookBorrow)==1)
            return true;
        return false;
    }
}
